package dao;

import java.util.List;

import model.Invoice;

import org.hibernate.SessionFactory;

public class InvoiceDAO {
	private final SessionFactory sf = util.NewHibernateUtil.getSessionFactory();

	@SuppressWarnings("unchecked")
	public List<Invoice> showAllInvoice() {
		try {
			sf.getCurrentSession().beginTransaction();
			return sf.getCurrentSession().createQuery("From Invoice").list();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	public List<Invoice> showAllInvoiceByAll(String key) {
		String hql = "FROM Invoice WHERE customerName like '%" + key
				+ "%' OR customerID LIKE '%" + key + "%'";
		sf.getCurrentSession().beginTransaction();
		List<Invoice> invoice = sf.getCurrentSession().createQuery(hql).list();
		sf.getCurrentSession().getTransaction().commit();
		return invoice;

	}

	@SuppressWarnings("unchecked")
	public List<Invoice> showAllInvoiceById(String key) {
		String hql2 = "from Invoice where invoiceID = " + key + "";
		sf.getCurrentSession().beginTransaction();
		List<Invoice> invoice = sf.getCurrentSession().createQuery(hql2).list();
		System.out.println(hql2);
		sf.getCurrentSession().getTransaction().commit();
		return invoice;

	}

	public boolean insertInvoice(Invoice in) {
		try {
			sf.getCurrentSession().beginTransaction();
			sf.getCurrentSession().save(in);
			sf.getCurrentSession().getTransaction().commit();
			return true;
		} catch (Exception em) {
			em.printStackTrace();
			sf.getCurrentSession().getTransaction().rollback();
			return false;
		}
	}

	public boolean deleteInvoice(Invoice in) {
		try {
			sf.getCurrentSession().beginTransaction();
			sf.getCurrentSession().delete(in);
			sf.getCurrentSession().getTransaction().commit();
			return true;
		} catch (Exception e2) {
			e2.printStackTrace();
			return false;
		}
	}

	public Invoice searchInvoice(int id) {
		try {
			sf.getCurrentSession().beginTransaction();
			Invoice inv = (Invoice) sf.getCurrentSession().get(Invoice.class,
					id);
			sf.getCurrentSession().getTransaction().commit();
			return inv;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	

}
